import { history } from 'umi';
import { message } from 'antd';
import { fakeAccountLogin, getFakeCaptcha } from './service';
import { getPageQuery, setAuthority } from './utils/utils';

const Model = {
  namespace: 'userAndlogin',
  state: {
    status: undefined,
  },
  effects: {
    *login({ payload }, { call, put }) {
      console.log(response,11111111111111111111111111111)
      const response = yield call(fakeAccountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      }); // Login successfully
      if (response.code == 200) {
        // 成功后把tokenhead和token放在sessiontoken里面
        if (response.data.type==3) {
          message.error('此账户缺乏相应权限');
          return;
         }
        sessionStorage.setItem('tokenHead',response.data.tokenHead)
        sessionStorage.setItem('token',response.data.token)
        sessionStorage.setItem('account',JSON.stringify(payload))       
        sessionStorage.setItem('personinfo',JSON.stringify(response.data))
        console.log(response, payload,1111111111111)
        message.success('登录成功！');
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        console.log(params)
        // let { redirect } = params;
        // if (redirect) {
        //   const redirectUrlParams = new URL(redirect);
        //   if (redirectUrlParams.origin === urlParams.origin) {
        //     redirect = redirect.substr(urlParams.origin.length);

        //     if (redirect.match(/^\/.*#/)) {
        //       redirect = redirect.substr(redirect.indexOf('#') + 1);
        //     }
        //   } else {
        //     window.location.href = redirect;
        //     return;
        //   }
        // }  
        // history.replace(redirect || '/');
            history.replace({
                pathname: '/dashboard/user-list',
               
              });
      }else{
        message.success(response.message);
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      let currentAuthority;
      // eslint-disable-next-line default-case
      switch (payload.data.type) {
        case 0:
          currentAuthority = 'admin'
          break;
        case 1:
          currentAuthority = 'admin1'
          break;
        case 2:
          currentAuthority = 'user'
          break;      
      }
      console.log(currentAuthority,payload,111111111111)
      setAuthority(currentAuthority);
      // type是登录方式手机登录还是邮箱登录 staus是状态码200表示o成功
      return { ...state, status: payload.code, type: 1 };
      
    },
  },
};
export default Model;
